<?php
class pk_sport extends BaseModel implements Retrievable {

	var $name;
	var $active;
	
    public function pk_sport($values) {
        parent::__construct($values);
    }

    public function validate() {
        $errors = Array();
		return (count($errors) === 0 ? true : $errors);
    }

    public static function get($id, $primaryKey='id') {
        return parent::get($id, __CLASS__, $primaryKey);
    }
    
    public static function getAll($searchArray=Array(), $sortArray=Array()) {
        return parent::getAll($searchArray, $sortArray, __CLASS__);
    }
    
    public static function getSportsOfTheDay() {    	
    	$date = date('m-d-Y');
    	$file = sprintf('%s/webroot/cache/%s_featured_sports.txt', DOC_ROOT, md5($date));
    	if(!file_exists($file)) {
    		$sports = pk_sport::getAll(array("active"=>"1"));
    		shuffle($sports);
    		$featured = $sports[0];
    		$fh = fopen($file, 'w');
    		if($fh) {
    			fwrite($fh, serialize($featured));
    			fclose($fh);
    		}
    	} else {
    		$featured = unserialize(file_get_contents($file));
    	}
    	return $featured;
    }
    
    public static function getFeaturedSport($sport="", &$homepage=false) {
    	$_sport = str_replace('-', ' ', $sport);
    	$featured = pk_sport::get($_sport, "name");
    	if($featured->id > 0) return $featured;
    	return pk_sport::getSportsOfTheDay();
    }
    
    public static function fillPair(&$data) {
    	//$sports = pk_sport::getAll(array("active"=>"1"));
    	$sports = pk_sport::getAll();
    	$pk_sport_ids = array();
    	$pk_sport_vals = array();
    	foreach($sports as $s) {
    		$pk_sport_ids[] = $s->id;
    		$pk_sport_vals[] = $s->name;
    	}
    	$data['pk_sport_ids'] = $pk_sport_ids;    	
    	$data['pk_sport_vals'] = $pk_sport_vals;
    }
    
    public static function toSportNames($ids) {
    	if(trim($ids) == '') return '';
    	
    	$idStr = str_replace(";", ",", $ids);
    	$sports = pk_sport::getAll(array("id"=>"[:custom] in($idStr)"));
    	$names = array();
    	foreach($sports as $s) {
    		$names[] = $s->name;
    	}
    	return implode(', ', $names);
    }
}
?>